package cn.com.aiton.common.netty.codec;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class NettyPosindaDecoder extends LengthFieldBasedFrameDecoder {
    Logger LOGGER = LoggerFactory.getLogger(NettyPosindaDecoder.class);

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) {
        if (in == null) {
            return null;
        }
        if (in.readableBytes() <= NettyPosindaProtocol.PACK_HEAD_LEN) {
            return null;
        }
        in.markReaderIndex();
        byte protocol = in.readByte();
        byte version = in.readByte();
        short retain = in.readShort();
        int length = in.readInt();
        int bytesLen = in.readableBytes();
        // FIXME 如果dataLength过大，可能导致问题
        if (bytesLen < length) {
            in.resetReaderIndex();
            return null;
        }
        byte[] bytes = new byte[bytesLen];
        in.readBytes(bytes);
        String str = new String(bytes, CharsetUtil.UTF_8);
        NettyPosindaProtocol customProtocol = new NettyPosindaProtocol();
        customProtocol.setProtocol(protocol);
        customProtocol.setVersion(version);
        customProtocol.setRetain(retain);
        customProtocol.setLen(length);
        customProtocol.setBody(str);
        LOGGER.warn("=======length:" + length + " ByteLen: " + bytesLen + "  CustomProtocol: " + customProtocol.toString());
        return customProtocol;
    }

    public NettyPosindaDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    public NettyPosindaDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    /**
     * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward
     * to the next {@link ChannelHandler} in the {@link ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }


}
